/*
 * author      : dormi330
 * date        : 2018/6/26
 * description : 订单取消
 */

package com.deep.trade.application.order;

import com.deep.trade.adaptor.required.member.Member;
import com.deep.trade.adaptor.required.member.MemberService;
import com.deep.trade.application.EventHub;
import com.deep.trade.common.CommonUtils;
import com.deep.trade.common.TradeException;
import com.deep.trade.domain.order.OrderRepository;
import com.deep.trade.domain.order.TradeOrder;
import com.deep.trade.order.dto.InDtoCancelOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CancelOrderService {
    private static final int ONLY_ONE_SHOULD_BE_UPDATED = 1;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private MemberService memberService;
    private OrderRepository orderRepository;
    private OrderQueryService orderQueryService;
    private EventHub eventHub;

    @Autowired
    public CancelOrderService(
            OrderRepository orderRepository
            , MemberService memberService
            , OrderQueryService orderQueryService
            , EventHub eventHub
    ) {
        this.orderRepository = orderRepository;
        this.memberService = memberService;
        this.orderQueryService = orderQueryService;
        this.eventHub = eventHub;
    }

    /**
     * 取消一个订单, 无须事务控制
     *
     * @throws Exception
     */
    @Transactional
    public void cancelTradeOrder(InDtoCancelOrder inDtoCancelOrder) throws Exception {
        logger.info("{}, tenantCode={}, inDtoCancelOrder={}", CommonUtils.currentClassAndMethod(), inDtoCancelOrder);

        // ====== public 入参检测 =======
        String tradeOrderId = inDtoCancelOrder.getTradeOrderId();
        if (null == tradeOrderId) throw new TradeException("tradeOrderId cannot be null");

        Member member = memberService.memberOfToken();
        if (null == member) throw new TradeException("memberId cannot be null");

        // ====== 获取领域对象 =======
        TradeOrder tradeOrder = orderQueryService.assureTradeOrder(tradeOrderId);
        if (!member.getId().equals(tradeOrder.getMemberId())) {
            throw new TradeException("the order's memberId doesn't match");
        }

        // ====== 领域对象操作 =======
        tradeOrder.cancel();

        // ====== 存储 =======
        if (ONLY_ONE_SHOULD_BE_UPDATED != orderRepository.updateTradeOrderStatus(tradeOrder)) {
            throw new TradeException("audit fail, cannot get order to audit");
        }

        // 领域事件 TODO
    }
}
